import HomeStore from '@/stores/home';
import { inject, observer } from 'mobx-react';
import React from 'react';
import { history } from 'umi';
import ListStore from '@/stores/list';
import CustomList from '@/components/custom_list';
import { message } from 'antd';
import { debounce, throttle } from 'lodash';

/**
 * 首页Props成员
 */
interface IndexPageProps {
  homeStore: HomeStore;
}

/**
 * 首页组件
 * inject、observer必须按照这个顺序写
 */
@inject('homeStore')
@observer
export default class IndexPage extends React.Component<IndexPageProps> {
  store = new ListStore();

  componentDidMount() {
    this.store.listNews();
  }

  onIncrementClick = () => {
    const { homeStore } = this.props;
    homeStore.increment();
  };

  onDecrementClick = () => {
    const { homeStore } = this.props;
    homeStore.decrement();
  };

  /**
   * 节流方法，防止连点
   */
  onLoadNewsListClick = throttle(
    () => {
      this.store.listNews();
    },
    500,
    { leading: true, trailing: false },
  );

  /**
   * 防抖方法，搜索实时出结果时使用
   */
  onTextInput = debounce(
    (text) => {
      message.info(`输入的内容为：${text}`);
    },
    500,
    { leading: false, trailing: true },
  );

  render() {
    const {
      homeStore: { number, sub10, md5 },
    } = this.props;
    const { newsList, newsListLoading } = this.store;

    return (
      <div style={{ width: '50%', display: 'flex', flexDirection: 'column' }}>
        <div>number {number}</div>
        <div>sub10 {sub10}</div>
        <div>md5 {md5}</div>
        <input onChange={(e) => this.onTextInput(e.currentTarget.value)} />

        <button onClick={this.onIncrementClick}>increase</button>
        <button onClick={this.onDecrementClick}>decrease</button>
        <button disabled={newsListLoading} onClick={this.onLoadNewsListClick}>
          loadNewsList
        </button>
        <CustomList
          dataSource={newsList}
          loading={newsListLoading}
          renderItem={(item, index) => {
            return (
              <div
                onClick={() => {
                  history.push({
                    pathname: '/info',
                    query: {
                      id: `${item.id}`,
                    },
                  });
                }}
                style={{
                  cursor: 'pointer',
                }}
              >
                {index + 1} {item.title}
              </div>
            );
          }}
          renderDivider={() => {
            return <div style={{ height: 1, backgroundColor: '#000' }} />;
          }}
        />
      </div>
    );
  }
}
